import 'package:flutter/cupertino.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/profile/models/model_question_items.dart';
import 'package:flutter_09_game/pages/profile/models/model_security_question.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:get/get.dart';

class ProfileEditSecurityQuestionLogic extends BaseController {
  List<ModelQuestionItems> questionItems = [];

  RxString questionRx = ''.obs;
  TextEditingController oldAnswerController = TextEditingController();

  TextEditingController answerController = TextEditingController();
  TextEditingController tipsController = TextEditingController();

  // 资金密码相关
  RxString fundPassword = ''.obs;

  RxBool isFormValid = false.obs;

  Rx<ModelSecurityQuestion> securityQuestion = Rx(ModelSecurityQuestion());

  @override
  void onInit() {
    super.onInit();
    _setupValidation();
    executeInitMethod(getQuestionItems);
    getUserSecurityQuestion();
  }

  /// 设置表单验证监听
  ///
  void _setupValidation() {
    // 监听所有字段变化，实时验证表单
    everAll([
      questionRx,
      fundPassword,
      // confirmPassword,
    ], (val) {
      clog('dasdasdasd');
      _validateForm();
    });

    // 监听文本控制器变化
    answerController.addListener(_validateForm);
    tipsController.addListener(_validateForm);
    oldAnswerController.addListener(_validateForm);
  }

  Future getQuestionItems() async {
    HttpResponse response = await HttpManager().get(
      API.getQuestion,
      fromJson: ModelQuestionItems.fromJson,
    );
    if (response.isSuccess) {
      questionItems = response.data;
      questionRx.value = questionItems.firstOrNull?.Content ?? "";
    }
  }

  getUserSecurityQuestion() async {
    HttpResponse response = await HttpManager().get(API.getUserSecurityQuestion,
        fromJson: ModelSecurityQuestion.fromJson);
    if (response.isSuccess) {
      securityQuestion.value = response.data;
    }
  }

  /// 表单验证
  void _validateForm() {
    final isValid = _isFormComplete();
    isFormValid.value = isValid;
  }

  /// 检查表单是否完整
  bool _isFormComplete() {
    return questionRx.value.isNotEmpty &&
        oldAnswerController.text.trim().isNotEmpty &&
        answerController.text.trim().isNotEmpty &&
        tipsController.text.trim().isNotEmpty &&
        fundPassword.value.length == 6;
  }

  /// 获取选中问题的ID
  int _getSelectedQuestionId() {
    final selectedQuestion = questionItems.firstWhere(
      (item) => item.Content == questionRx.value,
      orElse: () => questionItems.first,
    );
    return selectedQuestion.id ?? 1;
  }

  /// 设置资金密码
  Future<void> setFundPassword() async {
    final params = {
      'question_id': _getSelectedQuestionId(),
      'answer': oldAnswerController.text.trim(),
      'new_answer': answerController.text.trim(),
      'new_answer_notice': tipsController.text.trim(),
      'fund_password': fundPassword.value,
      'answer_notice': securityQuestion.value.notice,
    };

    HttpResponse response = await HttpManager().post(
      API.postUserChangeSecurityQuestion,
      params: params,
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.setSuccess.tr);
      // AppUserManager().refreshUserInfo();
      Get.back();
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    tipsController.dispose();
    answerController.dispose();
    oldAnswerController.dispose();
  }
}
